<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>熔断器测试页面</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #ff6b6b, #ee5a24);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .content {
            padding: 30px;
        }

        .test-section {
            margin-bottom: 40px;
            padding: 25px;
            border: 2px solid #e9ecef;
            border-radius: 10px;
            background: #f8f9fa;
        }

        .test-section h2 {
            color: #2c3e50;
            margin-bottom: 20px;
            font-size: 1.5em;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #34495e;
        }

        .form-group input, .form-group select {
            width: 100%;
            padding: 10px;
            border: 2px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-group input:focus, .form-group select:focus {
            outline: none;
            border-color: #3498db;
        }

        .btn {
            background: linear-gradient(135deg, #3498db, #2980b9);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s;
            margin-right: 10px;
            margin-bottom: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(52, 152, 219, 0.4);
        }

        .btn-danger {
            background: linear-gradient(135deg, #e74c3c, #c0392b);
        }

        .btn-danger:hover {
            box-shadow: 0 5px 15px rgba(231, 76, 60, 0.4);
        }

        .btn-success {
            background: linear-gradient(135deg, #27ae60, #229954);
        }

        .btn-success:hover {
            box-shadow: 0 5px 15px rgba(39, 174, 96, 0.4);
        }

        .result-area {
            margin-top: 20px;
            padding: 20px;
            background: #2c3e50;
            color: #ecf0f1;
            border-radius: 5px;
            font-family: 'Courier New', monospace;
            font-size: 14px;
            max-height: 400px;
            overflow-y: auto;
            white-space: pre-wrap;
        }

        .status-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-success { background-color: #27ae60; }
        .status-error { background-color: #e74c3c; }
        .status-warning { background-color: #f39c12; }
        .status-info { background-color: #3498db; }

        .grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .loading.show {
            display: block;
        }

        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #3498db;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .stats-panel {
            background: linear-gradient(135deg, #74b9ff, #0984e3);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }

        .stats-item {
            display: inline-block;
            margin-right: 30px;
            text-align: center;
        }

        .stats-value {
            font-size: 2em;
            font-weight: bold;
            display: block;
        }

        .stats-label {
            font-size: 0.9em;
            opacity: 0.8;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔧 熔断器测试中心</h1>
            <p>Spring Cloud CircuitBreaker 功能测试与演示</p>
        </div>

        <div class="content">
            <!-- 统计面板 -->
            <div class="stats-panel">
                <div class="stats-item">
                    <span class="stats-value" id="totalTests">0</span>
                    <span class="stats-label">总测试次数</span>
                </div>
                <div class="stats-item">
                    <span class="stats-value" id="successRate">0%</span>
                    <span class="stats-label">成功率</span>
                </div>
                <div class="stats-item">
                    <span class="stats-value" id="fallbackRate">0%</span>
                    <span class="stats-label">降级率</span>
                </div>
                <div class="stats-item">
                    <span class="stats-value" id="lastTestTime">-</span>
                    <span class="stats-label">最后测试时间</span>
                </div>
            </div>

            <div class="grid">
                <!-- 慢响应测试 -->
                <div class="test-section">
                    <h2><span class="status-indicator status-warning"></span>慢响应熔断测试</h2>
                    <div class="form-group">
                        <label for="slowDelay">延迟时间 (毫秒):</label>
                        <input type="number" id="slowDelay" value="5000" min="1000" max="30000">
                    </div>
                    <div class="form-group">
                        <label for="slowTimes">测试次数:</label>
                        <input type="number" id="slowTimes" value="3" min="1" max="20">
                    </div>
                    <button class="btn" onclick="testSlowResponse()">开始测试</button>
                    <button class="btn btn-success" onclick="clearResult('slowResult')">清空结果</button>
                    <div id="slowResult" class="result-area"></div>
                </div>

                <!-- 异常熔断测试 -->
                <div class="test-section">
                    <h2><span class="status-indicator status-error"></span>异常熔断测试</h2>
                    <div class="form-group">
                        <label for="errorRate">错误率 (%):</label>
                        <input type="number" id="errorRate" value="80" min="0" max="100">
                    </div>
                    <div class="form-group">
                        <label for="errorTimes">测试次数:</label>
                        <input type="number" id="errorTimes" value="10" min="1" max="50">
                    </div>
                    <button class="btn btn-danger" onclick="testErrorResponse()">开始测试</button>
                    <button class="btn btn-success" onclick="clearResult('errorResult')">清空结果</button>
                    <div id="errorResult" class="result-area"></div>
                </div>
            </div>

            <!-- 服务不可用测试 -->
            <div class="test-section">
                <h2><span class="status-indicator status-error"></span>服务不可用熔断测试</h2>
                <div class="form-group">
                    <label for="unavailableTimes">测试次数:</label>
                    <input type="number" id="unavailableTimes" value="5" min="1" max="20">
                </div>
                <button class="btn btn-danger" onclick="testUnavailableResponse()">开始测试</button>
                <button class="btn btn-success" onclick="clearResult('unavailableResult')">清空结果</button>
                <div id="unavailableResult" class="result-area"></div>
            </div>

            <!-- 综合测试 -->
            <div class="test-section">
                <h2><span class="status-indicator status-info"></span>综合熔断测试</h2>
                <p>执行包含正常调用、慢响应、高错误率和服务不可用的综合测试场景</p>
                <button class="btn btn-success" onclick="comprehensiveTest()">开始综合测试</button>
                <button class="btn btn-success" onclick="clearResult('comprehensiveResult')">清空结果</button>
                <div id="comprehensiveResult" class="result-area"></div>
            </div>

            <!-- 控制面板 -->
            <div class="test-section">
                <h2><span class="status-indicator status-info"></span>控制面板</h2>
                <button class="btn" onclick="getStats()">获取统计信息</button>
                <button class="btn" onclick="resetCounter()">重置计数器</button>
                <button class="btn btn-success" onclick="clearAllResults()">清空所有结果</button>
                <button class="btn btn-danger" onclick="location.reload()">刷新页面</button>
            </div>

            <!-- 加载指示器 -->
            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>测试进行中，请稍候...</p>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = 'http://localhost/circuit-breaker';
        let testStats = {
            total: 0,
            success: 0,
            error: 0,
            fallback: 0
        };

        // 显示加载状态
        function showLoading() {
            document.getElementById('loading').classList.add('show');
        }

        // 隐藏加载状态
        function hideLoading() {
            document.getElementById('loading').classList.remove('show');
        }

        // 更新统计信息
        function updateStats() {
            document.getElementById('totalTests').textContent = testStats.total;
            const successRate = testStats.total > 0 ? ((testStats.success / testStats.total) * 100).toFixed(1) : 0;
            const fallbackRate = testStats.total > 0 ? ((testStats.fallback / testStats.total) * 100).toFixed(1) : 0;
            document.getElementById('successRate').textContent = successRate + '%';
            document.getElementById('fallbackRate').textContent = fallbackRate + '%';
            document.getElementById('lastTestTime').textContent = new Date().toLocaleTimeString();
        }

        // 记录测试结果
        function recordTestResult(type) {
            testStats.total++;
            testStats[type]++;
            updateStats();
        }

        // 显示结果
        function displayResult(elementId, data, isError = false) {
            const element = document.getElementById(elementId);
            const timestamp = new Date().toLocaleTimeString();
            const status = isError ? '❌ 错误' : '✅ 成功';
            const result = `[${timestamp}] ${status}\n${JSON.stringify(data, null, 2)}\n\n`;
            element.textContent += result;
            element.scrollTop = element.scrollHeight;
        }

        // 清空结果
        function clearResult(elementId) {
            document.getElementById(elementId).textContent = '';
        }

        // 清空所有结果
        function clearAllResults() {
            ['slowResult', 'errorResult', 'unavailableResult', 'comprehensiveResult'].forEach(clearResult);
        }

        // 慢响应测试
        async function testSlowResponse() {
            const delay = document.getElementById('slowDelay').value;
            const times = document.getElementById('slowTimes').value;
            
            showLoading();
            try {
                const response = await fetch(`${API_BASE}/test-slow-response?delay=${delay}&times=${times}`);
                const data = await response.json();
                displayResult('slowResult', data);
                recordTestResult('success');
            } catch (error) {
                displayResult('slowResult', { error: error.message }, true);
                recordTestResult('error');
            } finally {
                hideLoading();
            }
        }

        // 异常测试
        async function testErrorResponse() {
            const errorRate = document.getElementById('errorRate').value;
            const times = document.getElementById('errorTimes').value;
            
            showLoading();
            try {
                const response = await fetch(`${API_BASE}/test-error-response?errorRate=${errorRate}&times=${times}`);
                const data = await response.json();
                displayResult('errorResult', data);
                recordTestResult('success');
            } catch (error) {
                displayResult('errorResult', { error: error.message }, true);
                recordTestResult('error');
            } finally {
                hideLoading();
            }
        }

        // 服务不可用测试
        async function testUnavailableResponse() {
            const times = document.getElementById('unavailableTimes').value;
            
            showLoading();
            try {
                const response = await fetch(`${API_BASE}/test-unavailable-response?times=${times}`);
                const data = await response.json();
                displayResult('unavailableResult', data);
                recordTestResult('success');
            } catch (error) {
                displayResult('unavailableResult', { error: error.message }, true);
                recordTestResult('error');
            } finally {
                hideLoading();
            }
        }

        // 综合测试
        async function comprehensiveTest() {
            showLoading();
            try {
                const response = await fetch(`${API_BASE}/comprehensive-test`);
                const data = await response.json();
                displayResult('comprehensiveResult', data);
                recordTestResult('success');
            } catch (error) {
                displayResult('comprehensiveResult', { error: error.message }, true);
                recordTestResult('error');
            } finally {
                hideLoading();
            }
        }

        // 获取统计信息
        async function getStats() {
            try {
                const response = await fetch(`${API_BASE}/stats`);
                const data = await response.json();
                alert(`统计信息:\n${JSON.stringify(data, null, 2)}`);
            } catch (error) {
                alert('获取统计信息失败: ' + error.message);
            }
        }

        // 重置计数器
        async function resetCounter() {
            try {
                const response = await fetch(`${API_BASE}/reset`, { method: 'POST' });
                const data = await response.json();
                alert('计数器已重置: ' + data.message);
                testStats = { total: 0, success: 0, error: 0, fallback: 0 };
                updateStats();
            } catch (error) {
                alert('重置计数器失败: ' + error.message);
            }
        }

        // 页面加载时初始化
        document.addEventListener('DOMContentLoaded', function() {
            updateStats();
            console.log('熔断器测试页面已加载');
        });
    </script>
</body>
</html>
